package com.zxh.blog.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zxh.blog.domain.Permission;
import com.zxh.blog.service.PermissionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/permission")
public class AdminPermissionController {

	@Autowired
	PermissionService permissionService;

	@RequiresPermissions("permission:read")
	@RequestMapping(value = "/index",method = RequestMethod.GET)
	public String index(){
		return "/permission/index.jsp";
	}

	@RequiresPermissions("permission:add")
	@RequestMapping(value = "/create",method = RequestMethod.POST)
	@ResponseBody
	public Map create(Permission permission){
		Date date = new Date();
//		permission.setCreate_time(date.toString());
//		permission.setUpdate_time(date.toString());
		Integer integer = permissionService.addPermission(permission);
		HashMap map = new HashMap();
		if(integer == 1){
			map.put("result","success");
		}else{
			map.put("result","fail");
		}
		return map;
	}

	@RequiresPermissions("permission:update")
	@RequestMapping(value = "/update",method = RequestMethod.POST)
	@ResponseBody
	public Map update(Permission permission){
		Date date = new Date();
//		permission.setUpdate_time(date.toString());
		permissionService.updatePermission(permission);
		HashMap map = new HashMap();
		if(true){
			map.put("result","success");
		}else{
			map.put("result","fail");
		}
		return map;
	}

	@RequiresPermissions("permission:delete")
	@RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET)
	@ResponseBody
	public Map delete(@PathVariable("ids") int[] ids){
		permissionService.deleteByIds(ids);
		HashMap map = new HashMap();
		if(true){
			map.put("result","success");
		}else{
			map.put("result","fail");
		}
		return map;
	}

	//@RequestParam(required = false, defaultValue = "0", value = "offset")
	//@RequestParam(required = false, defaultValue = "10", value = "limit")
	@RequiresPermissions("permission:read")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public Map list(@RequestParam int offset, @RequestParam int limit) {
		int a = (offset/limit)+1;
		PageHelper.startPage(a,limit);
		List<Permission> permissionList = permissionService.selectByList();
		PageInfo<Permission> p=new PageInfo<Permission>(permissionList);
		Map<String, Object> result = new HashMap();
		result.put("rows", p.getList());
		result.put("total", p.getTotal());
		return result;
	}

}
